﻿using System;
using System.Linq;
using Sustainalytics.DataLayer;
using System.Timers;
using Sustainalytics.Entities;

namespace Sustainalytics.News.BusinessLogic
{
    public class AutoUnpublishNews
    {
        private readonly INewsRepository _repository;
        private System.Timers.Timer timer;

        public AutoUnpublishNews(INewsRepository repository)
	    {
            // init news repo
            this._repository = repository;
            // run first time at start up
            timer_Elapsed(null, null);
	    }

         void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                // get UTC 2 days ago  and use as reference
                var reference = DateTime.UtcNow.Date.AddDays(-2);

                NewsServiceSerilog.Log.StartAutoUnpublish(DateTime.Now.ToString("s"), reference.ToString("s"));

                var list = _repository.ReadUnpublishedWithStatusActive(reference);
                var updates = list.Select(x => new Tuple<Guid, NewsStatus>(x, NewsStatus.Unpublished)).ToList();
                _repository.UpdateNewsToUnpublished(updates);
                
            }
            catch (Exception ex)
            {
                NewsServiceSerilog.Log.StartAutoUnpublishError(ex);
            }
            finally
            {
                // place the timer for the next run
                if (timer == null || !timer.Enabled)
                {
                    // reset timer 
                    var now = DateTime.UtcNow;
                    var nextrun = now.Date.AddDays(1) - now;
                    // run  next 00:00

                    timer = new System.Timers.Timer();
                    timer.Interval = nextrun.TotalMilliseconds;
                    timer.Elapsed += timer_Elapsed;
                    timer.AutoReset = false;
                    timer.Start();
                }

                NewsServiceSerilog.Log.StopAutoUnpublish(DateTime.Now.ToString("s"), DateTime.Now.AddMilliseconds(timer.Interval).ToString("s"));
            }
        }
    }
}
